// pages/crop/index.js
const api = require('../../request/api.js');
const util = require("../../utils/util")
let App = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
      barHeight:App.globalData.paddingTop,

        isShowCamera: false,
        // width: App.globalData.windowWidth,
        // height: App.globalData.windowHeight,
        // windowWidth: App.globalData.windowWidth,
        // windowHeight: App.globalData.windowHeight,
        src: "",
        path: "",
        image: "",
        skipphotoStatus: "0",// 1跳过 0没有跳过
        isShowImage: false,
        male: 1,
        yuejin: 0,
        age: 30,
        isIphoneX: App.globalData.isIphoneX,
        ctx: {},
        devicePosition: "front",
        isYuejin: 0,
        sex: [{ value: 0, name: '女' }, { value: 1, name: '男', checked: true },],
        yuejinList: [{ value: 1, name: '是' }, { value: 0, name: '否', checked: true },],
        modalName: null,
        isAnalyse: false,
        SystemHeight: 0,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "舌诊"
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let ctx = wx.createCameraContext()
        const SystemInfo = wx.getSystemInfoSync()
        this.setData({
            ctx: ctx,
            SystemHeight: SystemInfo.windowHeight
        })
        // let isIphoneX = App.globalData.isIphoneX;
        // debugger
        var that = this
        wx.authorize({
            scope: 'scope.camera',
            success: function (res) {
                that.setData({
                    isShowCamera: true,
                })
            },
            fail: function (res) {
                wx.showModal({
                    title: '请求授权您的摄像头',
                    content: '如需正常使用此小程序功能，请您按确定并在设置页面授权用户信息',
                    confirmText: '确定',
                    success: res => {
                        if (res.confirm) {
                            wx.openSetting({
                                success: function (res) {
                                    if (res.authSetting['scope.camera']) { //设置允许获取摄像头
                                        wx.showToast({
                                            title: '授权成功',
                                            icon: 'success',
                                            duration: 1000
                                        })
                                        that.setData({
                                            isShowCamera: true,
                                        })

                                    } else { //不允许
                                        wx.showToast({
                                            title: '授权失败',
                                            icon: 'none',
                                            duration: 1000
                                        })
                                        wx.navigateBack()
                                    }
                                }
                            })
                        } else { //取消
                            wx.showToast({
                                title: '授权失败',
                                icon: 'none',
                                duration: 1000
                            })
                            wx.navigateBack()
                        }
                    }
                })

            }
        })
        // wx.getStorage({
        //   key: 'male',
        //   success (res) {
        //     that.setData({
        //       male: res.data
        //     })
        //   }
        // })
        // wx.getStorage({
        //   key: 'yuejin',
        //   success (res) {
        //     that.setData({
        //       yuejin: res.data 
        //     })
        //   }
        // })
        // wx.getStorage({
        //   key: 'age',
        //   success (res) {
        //     that.setData({
        //       age: res.data
        //     })
        //   }
        // })
    },
    /**
     * 拍照
     */
    takePhotoAction: function () {
        var that = this
        that.data.ctx.takePhoto({
            quality: 'normal', //high 高质量 normal low
            success: (res) => {
                that.loadTempImagePath(res.tempImagePath);
            },
        })
    },
    /**
     * 改变摄像头
     */
    changeCameraAction: function (e) {
        var that = this
        let devicePosition = that.data.devicePosition

        that.setData({
            devicePosition: devicePosition == "back" ? "front" : "back"
        })
    },
    cancel: function (e) {
        this.setData({
            isShowImage: false
        })
    },
    changeSex(e) {
        this.setData({
            male: Number(e.detail.value),
            yuejin: Number(e.detail.value)
        })
        wx.setStorage({
            key: "male",
            data: this.data.male

        })
    },
    changeYuejin(e) {
        this.setData({
            yuejin: Number(e.detail.value)
        })
        wx.setStorage({
            key: "yuejin",
            data: this.data.yuejin

        })
    },
    setAge(e) {
        this.setData({
            age: e.detail.value
        })
        wx.setStorage({
            key: "age",
            data: e.detail.value

        })
    },
    showModal(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
            modalName: null
        })
    },
    startCheck: function (e) {
        if (!this.data.age) {
            util.showToast("请输入年龄")
            return
        }
        //console.log('智能分析中')
        util.showToast('智能分析中...')
        this.setData({
            isAnalyse: true
        })
        this.hideModal()
        let that = this
        const authorization = ''
        const AppId = ''
        const userKey = ''
        wx.uploadFile({
            url: 'https://api.aikanshe.com/agency/quanxi',
            filePath: that.data.path,
            name: 'file',
            header: {
                authorization: authorization,
                AppId: AppId
            },
            formData: {
                userKey: userKey,
                isFrontCamera: that.data.devicePosition == "front",
                male: that.data.male,
                Appkey: 'klgbboskmj3kx3zqofr9m4p5qnmnnqeq',
                age: that.data.age,
                isYuejin: that.data.yuejin
            },
            success(res) {
                // util.hideLoading();
                if (res.statusCode != 200) {
                    util.showToast("目前使用人数过多，请稍后再试", "cancel")
                    setTimeout(() => {
                        that.setData({
                            isAnalyse: false
                        })
                    }, 1000);
                    return
                }
                // 判断是否成功
                let jsonObj = JSON.parse(res.data)
                if (jsonObj.meta.code == "40001") {
                    that.setData({
                        isAnalyse: false
                    })
                    // 设置本地看舌次数，超过三次提示分享
                    // let count = parseInt(wx.getStorageSync('count'))

                    // if (!count){
                    //   count = 0
                    // }
                    // wx.setStorage({
                    //   key: 'count',
                    //   data: count + 1,
                    // })
                    // debugger
                    // 跳转到结果页
                    let history_id = jsonObj.data.id
                    let tizhi_table_data = {
                        tizhi_tableXData: jsonObj.data.tizhiTableXData,
                        tizhi_tableYData: jsonObj.data.tizhiTableYData
                    }
                    console.log(tizhi_table_data)
                    if (history_id > 0) {
                        wx.setStorage({
                            key: "tongue_path",
                            data: jsonObj.data.tonguePicAddr
                        })

                        wx.setStorage({
                            key: "result",
                            data: jsonObj.data
                        })
                        wx.navigateTo({
                            url: `/pages/tongue/detail?from=temp&id=${history_id}&tizhiTableData=${JSON.stringify(tizhi_table_data)}`
                        })

                    }
                } else {
                    util.showToast("未检测到舌头，请按要求重新拍照上传", "cancel")
                    setTimeout(() => {
                        that.setData({
                            isAnalyse: false
                        })
                    }, 1000);
                }
            }
        })
    },
    /**
     * 从相册选取
     */
    selectPhotoAction: function (e) {
        var that = this
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths
                //console.log(tempFilePaths[0]);
                that.loadTempImagePath(tempFilePaths[0]);
            }
        })
    },
    loadTempImagePath: function (options) {
        var that = this
        that.setData({
            path: options,
            isShowImage: true
        })

    },
    goExample(e) {
        wx.navigateTo({
            url: '/pages/example/index'
        })
    },
})